<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;

class SystemSetting extends Model
{
    protected $fillable = [
        'group',
        'key',
        'value',
        'type',
        'label',
        'description',
        'is_public',
        'sort_order',
    ];

    protected $casts = [
        'is_public' => 'boolean',
        'sort_order' => 'integer',
    ];

    /**
     * 获取配置值（带类型转换）
     */
    public function getTypedValue()
    {
        return match($this->type) {
            'number' => (float) $this->value,
            'boolean' => filter_var($this->value, FILTER_VALIDATE_BOOLEAN),
            'json' => json_decode($this->value, true),
            'file' => $this->value, // 文件类型直接返回路径
            default => $this->value,
        };
    }

    /**
     * 获取单个配置值（带缓存和层级获取）
     */
    public static function get(string $key, $default = null)
    {
        return Cache::remember("system_setting_{$key}", 3600, function () use ($key, $default) {
            $setting = self::where('key', $key)->first();
            $value = $setting ? $setting->getTypedValue() : null;
            
            // 如果配置值为 null 或空字符串，尝试从配置文件获取
            if ($value === null || $value === '') {
                $value = self::getFallbackValue($key, $default);
            }
            
            return $value ?? $default;
        });
    }
    
    /**
     * 获取后备值（从配置文件）
     */
    protected static function getFallbackValue(string $key, $default = null)
    {
        return match($key) {
            'site_name' => config('app.name', $default),
            'seo_title' => config('app.name', $default),
            default => $default,
        };
    }

    /**
     * 获取分组配置（带缓存）
     */
    public static function getGroup(string $group): array
    {
        return Cache::remember("system_settings_group_{$group}", 3600, function () use ($group) {
            return self::where('group', $group)
                ->orderBy('sort_order')
                ->get()
                ->mapWithKeys(function ($setting) {
                    return [$setting->key => $setting->getTypedValue()];
                })
                ->toArray();
        });
    }

    /**
     * 获取所有公开配置（带层级获取）
     */
    public static function getPublic(): array
    {
        return Cache::remember('system_settings_public', 3600, function () {
            $settings = self::where('is_public', true)
                ->get()
                ->mapWithKeys(function ($setting) {
                    $value = $setting->getTypedValue();
                    
                    // 如果值为 null 或空字符串，尝试从配置文件获取
                    if ($value === null || $value === '') {
                        $value = self::getFallbackValue($setting->key, null);
                    }
                    
                    return [$setting->key => $value];
                })
                ->toArray();
            
            return $settings;
        });
    }

    /**
     * 设置配置值
     */
    public static function set(string $key, $value): bool
    {
        $setting = self::where('key', $key)->first();
        
        if (!$setting) {
            return false;
        }

        // 类型转换
        $typedValue = match($setting->type) {
            'boolean' => $value ? '1' : '0',
            'json' => is_array($value) ? json_encode($value) : $value,
            default => (string) $value,
        };

        $setting->update(['value' => $typedValue]);
        
        // 清除缓存
        self::clearCache($key, $setting->group);
        
        return true;
    }

    /**
     * 清除缓存
     */
    public static function clearCache(?string $key = null, ?string $group = null): void
    {
        if ($key) {
            Cache::forget("system_setting_{$key}");
        }
        
        if ($group) {
            Cache::forget("system_settings_group_{$group}");
        }
        
        Cache::forget('system_settings_public');
    }

    /**
     * 获取所有公开配置（前端可访问）
     */
    public static function getPublicSettings(): array
    {
        return Cache::remember('system_settings_public', 3600, function () {
            return self::where('is_public', true)
                ->orderBy('group')
                ->orderBy('sort_order')
                ->get()
                ->mapWithKeys(function ($setting) {
                    return [$setting->key => $setting->getTypedValue()];
                })
                ->toArray();
        });
    }

    /**
     * 模型事件
     */
    protected static function booted(): void
    {
        static::saved(function ($setting) {
            self::clearCache($setting->key, $setting->group);
            // 清除公开配置缓存
            Cache::forget('system_settings_public');
        });

        static::deleted(function ($setting) {
            self::clearCache($setting->key, $setting->group);
            // 清除公开配置缓存
            Cache::forget('system_settings_public');
        });
    }
}
